package com.huawei.esdk.tpoa.business.oa.sitemgr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import com.huawei.esdk.platform.authorize.itf.IAuthorize;
import com.huawei.esdk.platform.common.SDKResult;
import com.huawei.esdk.platform.common.ThreadLocalHolder;
import com.huawei.esdk.platform.common.bean.aa.AccountInfo;
import com.huawei.esdk.platform.common.config.ConfigManager;
import com.huawei.esdk.platform.common.constants.ESDKConstant;
import com.huawei.esdk.platform.common.exception.SDKException;
import com.huawei.esdk.platform.common.utils.StringUtils;
import com.huawei.esdk.tp.authorize.SessionManager;
import com.huawei.esdk.tp.common.constants.InfoKeys;
import com.huawei.esdk.tp.common.constants.TPConstant;
import com.huawei.esdk.tp.domain.model.Site;
import com.huawei.esdk.tp.domain.model.bean.PagedList;
import com.huawei.esdk.tp.domain.model.bean.QuerySites;
import com.huawei.esdk.tp.domain.model.bean.SortField;
import com.huawei.esdk.tpoa.business.oa.mapping.TPOADataMapping;

public class TPOASiteManager extends Thread
{
    public final static Map<String, Site> tpSites = new HashMap<String, Site>();
    
    public final static Map<String, Site> exchangeSites = new HashMap<String, Site>();
    
    private static final Logger LOGGER = Logger.getLogger(TPOASiteManager.class);
    
    private IAuthorize authorize;
    
    private ExecutorService es = Executors.newCachedThreadPool();
    
    public void init()
    {
        this.start();
    }

    @Override
    public void run()
    {
        ThreadLocalHolder.get().getEntities().put(ESDKConstant.CURRENT_PRODUCT, "tpoa");
//        authorize.setAuthPolicy("tpoa", ESDKConstant.AUTH_POLICY_SINGLE_ACCT);
        
        AccountInfo esdkAcct = new AccountInfo();
        ThreadLocalHolder.get().getEntities().put(ESDKConstant.ACCT_INFO_ESDK, esdkAcct);
        ThreadLocalHolder.get().getEntities().put(InfoKeys.SDK_SESSION_ID.toString(), "");
        
        SessionManager sessionMgr = SessionManager.getInstance();
        sessionMgr.saveSDKSession(TPConstant.SMC_LOGIN_CLIENT_TYPE_OA);
        
        try
        {
            //获取所有TP会场
            loadAllTPSites();
            
            //获取所有Exchange room resource
            loadAllExchangeSites();
            
            //为TP会场和Exchange room resource 创建映射关系
            createTPOASiteMapping();
            
            //启动会场同步线程
            TPOASiteSynchronization siteSynchronization = new TPOASiteSynchronization();
            siteSynchronization.init();
            
            es.execute(siteSynchronization);
        }
        catch (SDKException e)
        {
            LOGGER.error("loadAllTPSites method error", e);
        }
        catch (Exception e)
        {
            LOGGER.error("loadAllExchangeSites method error", e);
        }
    }
    
    public void destroy()
    {
        es.shutdownNow();
    }
    
    public void loadAllTPSites()
        throws SDKException
    {
        QuerySites querySites = new QuerySites();
        int currentPage = 1;
        querySites.setCurrentPage(currentPage);
        
        int numberPerPage = 50;
        String numberPerPageStr = ConfigManager.getInstance().getValue("tpoa_queryAllSites_numberPerPage");
        if (!StringUtils.isEmpty(numberPerPageStr))
        {
            try
            {
                numberPerPage = Integer.parseInt(numberPerPageStr);
            }
            catch (NumberFormatException e)
            {
                LOGGER.error("NumberFormatException for numberPerPageStr,set default value 50", e);
                numberPerPage = 50;
            }
        }
        
        querySites.setNumberPerPage(numberPerPage);
        List<SortField> sortFields = new ArrayList<SortField>();
        querySites.setSortField(sortFields);
        
        SDKResult<PagedList<Site>> sites = null;
        
        boolean flag = true;
        
        while (flag)
        {
            try
            {  
                sites = Site.querySites(querySites);
            }
            catch (Exception e)
            {
                try
                {
                    Thread.sleep(30 * 1000);
                    continue;
                }
                catch (InterruptedException e1)
                {
                    LOGGER.error(e1);
                }
            }
            
            if (null != sites && 0 == sites.getErrCode())
            {
                PagedList<Site> sitePagedList = sites.getResult();
                for (Site site : sitePagedList.getRecords())
                {
                    tpSites.put(site.getUri(), site);
                }
                int curPageNo = sitePagedList.getCurPageNo();
                int totalPageCount = sitePagedList.getTotalPageCount();
                if (curPageNo < totalPageCount)
                {
                    querySites.setCurrentPage(curPageNo + 1);
                }
                else
                {
                    flag = false;
                }
            }
            else
            {
                flag = false;
            }
        }
        
    }
    
    public void loadAllExchangeSites()
        throws Exception
    {
        Site site = new Site();
        SDKResult<List<Site>> response = null;
        try
        {
            response = site.queryExchangeSites();
        }
        catch (SDKException e)
        {
            LOGGER.error("loadAllExchangeSites method error", e);
            throw new Exception("loadAllExchangeSites method error:" + e);
        }
        
        if (null != response && 0 == response.getErrCode())
        {
            List<Site> sites = response.getResult();
            for (Site siteInfo : sites)
            {
                exchangeSites.put(siteInfo.getUri(), siteInfo);
            }
        }
        else
        {
            String errorInfo = "";
            if (null != response)
            {
                errorInfo = response.getDescription();
            }
            throw new Exception("loadAllExchangeSites method error:" + errorInfo);
        }
    }
    
    public void createTPOASiteMapping()
    {
        
        for (Entry<String, Site> exchangeSite : exchangeSites.entrySet())
        {
            String mailAddress = exchangeSite.getKey();
            
            String tpSiteUri = getTargetMappingStrAD2TP(mailAddress);
            
            if (tpSites.containsKey(tpSiteUri))
            {
                TPOADataMapping.siteUriMapping.put(mailAddress, tpSiteUri);
            }
        }
        
    }
    
    //当前为邮箱地址映射方式，获取@之前的字符串
    private String getTargetMappingStrAD2TP(String param)
    {
        
        if (null == param || param.isEmpty())
        {
            return null;
        }
        
        if (param.indexOf("@") == -1)
        {
            return null;
        }
        
        return param.substring(0, param.indexOf("@"));
        
    }
    
    public IAuthorize getAuthorize()
    {
        return authorize;
    }
    
    public void setAuthorize(IAuthorize authorize)
    {
        this.authorize = authorize;
    }
}
